<template>
  <div class="container">
    <div class="demo-video">
      <!-- <vue3VideoPlay v-if="ifShow" class="video-player" v-bind="options" /> -->
      <video ref="videoElement" id="videoElement" controls muted
        style="width: 100%; height: 100%; object-fit: fill"></video>
    </div>
  </div>

</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch, onUnmounted } from 'vue';
import Hls from 'hls.js'

let videoElement = ref()
let hls = null // 定义的hls对象
let props = defineProps({
  url: {
    type: String,
    default: ''
  }
})

watch(props,()=>{
  if (hls) {
    hls.destroy();
    hls=null
  }
  initVideo()
})

// 视频加载
let video = document.getElementById('video') // 定义挂载节点
const initVideo = () => {
  if(props.url==null||props.url=='') return 
  if (Hls.isSupported()) {
    hls = new Hls();
    hls.loadSource(props.url); // 设置播放路径
    hls.attachMedia(videoElement.value); // 解析到video标签上
    hls.on(Hls.Events.MANIFEST_PARSED, function () {
      videoElement.value.play(); // 播放视频
    });
  } else if (video.canPlayType('application/vnd.apple.mpegurl')) { // 如果浏览器原生支持HLS
    videoElement.value.src = url;
    videoElement.value.addEventListener('loadedmetadata', function () {
      videoElement.value.play();
    });
  }
}
onMounted(()=>{
  initVideo()
})
// 最后离开页面的时候，记得销毁
onUnmounted(() => {
  if (hls) {
    hls.destroy();
  }
});
</script>

<style scoped lang="scss">
.container {
  background-color: black;
  width: 100%;
  height: 100%;
  display: flex;
  box-sizing: border-box;
  overflow: hidden;

  .demo-video {
    flex: 1;
    width: 100%;
    max-height: 100%;
    display: flex;

    :deep(video) {
      object-fit: contain;
    }
  }
}
</style>
